<template>
  <div class="test">
    <a id="downLoadLink" style="display: none"></a>
    <video ref="videoRef" class="video"></video>
    <el-button type="primary" @click="start">开始录制</el-button>
    <el-button type="primary" @click="stop">停止录制</el-button>
    <p class="time">当前时间戳： {{ currentTime }}</p>
  </div>
</template>

<script setup name="index">
import {ref} from 'vue'
import moment from 'moment'

const videoRef = ref(null)
const mediaStream = ref(null)

const recordedBlobs = ref([])

const currentTime = ref('')

setInterval(() => {
  currentTime.value = moment().format('YYYY-MM-DD HH:mm:ss')
}, 1000)

// 打开摄像头
const openCamera = async () => {
  try {
    // 判断浏览器mediaDevices兼容支持情况
    if (navigator.mediaDevices) {
      const _mediaStream = await navigator.mediaDevices.getUserMedia({video: true, audio: true})
      videoRef.value.srcObject = _mediaStream
      mediaStream.value = _mediaStream
      videoRef.value.onloadedmetadata = () => {
        videoRef.value.play()
      }
    }
  }catch (e) {
    console.log(e, '123e')
  }
}

// 页面静音
const mutePage = () => {
  document.querySelectorAll('video, audio').forEach((elem) => {
    elem.muted = true
    elem.pause()
  })
}

// 开始录制
const start = () => {
  openCamera()
  mutePage()
  setTimeout(() => {
    // 方法区
    record()
  }, 2000)
}

// 停止录制
const stop = () => {
  if (!videoRef.value.srcObject) return
  const tracks = videoRef.value.srcObject.getTracks()
  // 关闭摄像头和音频
  tracks.forEach((track) => {
    track.stop()
  })
}

// 截取视频流
const record = () => {
  let mediaRecorder
  let options
  if (typeof MediaRecorder.isTypeSupported === 'function') {
    // 根据浏览器来设置编码参数
    if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
      options = {
        MimeType: 'video/webm;codecs=h264'
      }
    } else if (MediaRecorder.isTypeSupported('video/webm;codecs=h264')) {
      options = {
        MimeType: 'video/webm;codecs=h264'
      }
    } else if (MediaRecorder.isTypeSupported('video/webm;codecs=vp8')) {
      options = {
        MimeType: 'video/webm;codecs=vp8'
      }
    }
    mediaRecorder = new MediaRecorder(mediaStream.value, options)
  } else {
    mediaRecorder = new MediaRecorder(mediaStream.value)
  }
  mediaRecorder.start()
  // 视频录制监听事件
  mediaRecorder.ondataavailable = (e) => {
    console.log(e, '视频录制监听事件')
    // 录制的视频数据有效
    if (e.data && e.data.size > 0) {
      recordedBlobs.value.push(e.data)
    }
  }
  // 停止录像后增加下载视频功能，将视频流转为mp4格式
  mediaRecorder.onstop = () => {
    const blob = new Blob(recordedBlobs.value, { type: 'video/mp4' })
    recordedBlobs.value = []
    // 将视频链接转换完可以用于在浏览器上预览的本地视频
    const videoUrl = window.URL.createObjectURL(blob)
    // 设置下载链接
    document.getElementById('downLoadLink').href = videoUrl
    // 设置下载mp4格式视频
    document.getElementById('downLoadLink').download = 'media.mp4'
    document.getElementById('downLoadLink').innerHTML = 'DownLoad video file'
    // 生成随机数字
    const rand = Math.floor(Math.random() * 1000000)
    // 生成视频名
    const name = `video${rand}`

    // setAttribute() 方法添加指定的属性，并为其赋指定的值
    document.getElementById('downLoadLink').setAttribute('download', name)
    document.getElementById('downLoadLink').setAttribute('name', name)

    console.log(name)
    const filename = 'C:\\Users\\k1114\\Downloads\\' + name
    console.log(filename)

    // 0.5s后自动下载视频
    setTimeout(() => {
      document.getElementById('downLoadLink').click()
    }, 500)
  }}
</script>

<style lang="less" scoped>
.test{
}
</style>
